<template>
  <view class="container">
    <!-- 选择头像区域 -->
    <view class="input-container">
      <text class="input-label">头像：</text>
      <view class="avatar-field">
        <button open-type="chooseAvatar" @chooseavatar="onChooseAvatar" class="avatar-btn">
          <image :src="avatarUrl || '/static/ava.png'" mode="aspectFill" class="avatar-img" />
        </button>
      </view>
    </view>

    <!-- 昵称输入框 -->
    <view class="input-container">
      <text class="input-label">昵称：</text>
      <input class="input-field" type="nickname" :value="nickname" @input="handleInputChange" placeholder="请输入昵称" />
    </view>

    <!-- 电话输入框 -->
    <view class="input-container">
      <text class="input-label">电话：</text>
      <input class="input-field" type="number" :value="tel" @input="handleTelChange" placeholder="请输入电话" />
    </view>

    <!-- 密码输入框 -->
    <view class="input-container">
      <text class="input-label">密码：</text>
      <input class="input-field" password :value="pass" @input="handlePassChange" placeholder="请输入密码" />
    </view>

    <!-- 注册并登录按钮 -->
    <button @click="authorizeLogin" class="login-btn">
      注册并登录
    </button>
  </view>
</template>

<script>
export default {
  data() {
    return {
      code: '',  // 存储登录凭证
      userInfo: {
        nickName: '', // 用户昵称
        avatarUrl: '', // 用户头像
      },
      nickname: '',  // 用户昵称
      openid: '',  // 用于存储openid
      tel: '',  // 用户电话
      pass: '',  // 密码
      avatarUrl: '',  // 用户头像 URL
    };
  },
  mounted() {
    // 页面加载时检查是否已经存储了用户信息
    const storedUserInfo = uni.getStorageSync('userInfo');
    if (storedUserInfo) {
      this.userInfo = storedUserInfo;
      this.nickname = storedUserInfo.nickName;
      this.avatarUrl = storedUserInfo.avatarUrl;
      // 跳过登录，直接进入首页
      uni.navigateTo({
        url: '/pages/home/home',  // 跳转到 list 页面
      });
    }
  },
  methods: {
    // 选择头像
    onChooseAvatar(e) {
      const { avatarUrl } = e.detail;
      this.avatarUrl = avatarUrl;  // 更新头像 URL
      this.userInfo.avatarUrl = avatarUrl;  // 同步到 userInfo
    },

    // 处理昵称输入变化
    handleInputChange(e) {
      this.nickname = e.detail.value;  // 更新昵称
      this.userInfo.nickName = e.detail.value;  // 同步到 userInfo
    },

    // 处理电话输入变化
    handleTelChange(e) {
      this.tel = e.detail.value;  // 更新电话
    },

    // 处理密码输入变化
    handlePassChange(e) {
      this.pass = e.detail.value;  // 更新密码
    },

    // 授权登录
    authorizeLogin() {
      const { userInfo, nickname, tel, pass } = this;

      // 判断头像、昵称、电话和密码是否填写完整
      if (!userInfo.avatarUrl) {
        uni.showToast({
          title: '请上传头像',
          icon: 'none',
          duration: 2000
        });
        return;
      }
      
      if (!nickname) {
        uni.showToast({
          title: '请填写昵称',
          icon: 'none',
          duration: 2000
        });
        return;
      }
      
      if (!tel) {
        uni.showToast({
          title: '请填写电话',
          icon: 'none',
          duration: 2000
        });
        return;
      }
      
      if (!pass) {
        uni.showToast({
          title: '请填写密码',
          icon: 'none',
          duration: 2000
        });
        return;
      }

      // 获取登录凭证并请求 session_key
      uni.login({
        success: (res) => {
          if (res.code) {
            this.code = res.code;
            this.getSessionKey(res.code);  // 请求 session_key
          } else {
            console.error('登录失败！' + res.errMsg);
          }
        },
        fail: (err) => {
          console.error('登录失败', err);
        }
      });
    },

    // 请求接口获取 session_key
    getSessionKey(code) {
      const appid = 'wx3c0518fdc0f73347';
      const secret = 'ecec3ad8ba75497227d4dbf316c6c336';

      uni.request({
        url: 'https://yiliao.kuxia.top/app/user/getsessionkey', 
        method: 'POST',
        data: { code, appid, secret },
        success: (res) => {
          if (res.statusCode === 200 && res.data.code === 1) {
            this.openid = res.data.data.openid;
            this.sendUserInfo();  // 请求 session_key 成功后提交用户信息
          } else {
            console.error('请求失败:', res.data.message || res.data.msg);
          }
        },
        fail: (err) => {
          console.error('请求失败:', err.message);
        }
      });
    },

    // 提交用户信息
    sendUserInfo() {
      const { userInfo, openid, tel, pass } = this;

      if (!userInfo.avatarUrl || !openid || !userInfo.nickName) {
        console.error('头像、昵称或openid未填写');
        return;
      }

      // 准备请求参数，确保与接口要求匹配
      const userData = {
        openid: openid,  // 必须传递openid
        avatar: userInfo.avatarUrl,  // 传递头像URL
        nickname: userInfo.nickName,  // 传递昵称
        tel: tel,  // 电话
        pass: pass,  // 密码
      };

      uni.request({
        url: 'https://yiliao.kuxia.top/app/user/empower',  // 后端接口
        method: 'POST',
        data: userData,
        success: (res) => {
          if (res.data.code === 1) {
            uni.request({
              url: "https://yiliao.kuxia.top/app/user/index",
              method: "POST",
              data: {
                tel: tel,
                pass: pass,
              },
              success: (res) => {
                if (res.data.code === 1) {
                  // 登录成功，将用户信息存储到本地
                  	uni.setStorage({
					key: 'user',
					data: res.data,
					success: function () {
						console.log('数据存储成功');
					}
				});
                  uni.setStorageSync("data", JSON.stringify(res.data)); // 存储用户信息
                  uni.setStorageSync("tel", tel); // 存储电话
                  uni.setStorageSync("pass", pass); // 存储密码

                  uni.showToast({
                    title: "登录成功",
                    icon: "success",
                    duration: 2000,
                  });

                  setTimeout(() => {
                    // 跳转到主页
                    uni.reLaunch({
                    	url: "/pages/home/home",
                    });
                  }, 2000);
                } else {
                  uni.showToast({
                    title: "密码有误，请检查！",
                    icon: "none",
                    duration: 2000,
                  });
                }
              },
              fail: () => {
                uni.showToast({
                  title: "账号不存在或密码错误",
                  icon: "none",
                  duration: 2000,
                });
              },
            });

            // 登录成功后，将用户信息存储到本地
            uni.setStorageSync('userInfo', userInfo);
          } else {
            console.error('请求失败:', res.data.message || res.data.msg);
            uni.showToast({
              title: '请求失败',
              icon: 'none',
            });
          }
        },
        fail: (err) => {
          console.error('请求失败:', err.message);
          uni.showToast({
            title: '请求失败',
            icon: 'none',
          });
        }
      });
    }
  }
};
</script>

<style scoped>
.container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-start;
  height: 100vh;
  padding: 20px;
  box-sizing: border-box;
}

.input-container {
  display: flex;
  align-items: center;
  width: 100%;
  margin-bottom: 20px;
  padding: 0 10px;
  box-sizing: border-box;
}

.input-label {
  width: 20%;
  font-size: 16px;
  color: #333;
}

.input-field {
  flex: 1;
  height: 40px;
  border: 1px solid #ddd;
  border-radius: 5px;
  padding: 0 10px;
  font-size: 16px;
}

.avatar-field {
  flex: 1;
  display: flex;
  align-items: center;
}

.avatar-btn {
  width: 50px;
  height: 50px;
  border-radius: 10%;
  overflow: hidden;
  background-color: #f0f0f0;
  justify-content: center;
  margin-left: 10px;
  border: none;
}

.avatar-img {
  width: 50px;
  height: 50px;
  margin-left: -15px;
}

.avatar-text {
  color: #666;
  font-size: 14px;
}

.login-btn {
  width: 80%;
  height: 45px;
  background-color: #13AF12;
  color: white;
  font-weight: 700;
  font-size: 18px;
  margin-top: 20px;
  border: none;
}
</style>
    